<template>
    <div class="course-list flex flex-col sm:flex-row dark:bg-regal-dark w-full">
        <div :class="'w-full ml-0 sm:ml-2 mt-2 sm:mt-0' ">
            <Search :search="search" :reset="reset">
                <template v-slot:body>
                    <el-form-item label="日期">
                        <el-date-picker
                            v-model="timeArr"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                        />
                    </el-form-item>
                </template>
            </Search>
            <div class="table-default course-table">
                <div class="pt-5 pl-2">
                    <el-button type="primary" @click="editCourse"><Icon name="plus" className="w-4 h-4 mr-1" /> 修改上课时间</el-button>
                </div>
                <table class="table mt-3">
                    <tr class="course-header">
                        <td v-for="item in headerConfig">
                            <div class="weekText">{{item.label}}</div>
                            <div class="date" v-if="item.prop != 'time'">{{item.prop}}</div>
                        </td>
                    </tr>
                    <tr class="course-tr" v-for="item in tableData" :key="item.time">
                        <td class="time">{{item.time}}</td>
                        <td class="course-item" v-for="day in headerConfig.slice(1)" :key="day.prop">
                            <div class="active" v-if="item.customerList[day.prop]?.customer_name">
                                <p>用户：{{ item.customerList?.[day.prop].customer_name }}</p>
                                <p>课程：{{ item.customerList?.[day.prop].subject_name }}</p>
                                <p class="flex mt-3 justify-between">
                                    <el-tag :type="statusTagColor[item.customerList?.[day.prop].status].value">{{statusTagColor[item.customerList?.[day.prop].status].label}}</el-tag>
                                    <el-button  @click="cancel(item.customerList?.[day.prop].reservation_id)" type="primary" link v-if="item.customerList?.[day.prop].status == 1">取消预约</el-button>
                                    <el-button type="primary" link v-if="item.customerList?.[day.prop].status == 4">修改实销课时</el-button>
                                </p>
                            </div>
                            <div v-else style="width: 192px"></div>
                        </td>
                    </tr>
                </table>
            </div>

            <el-dialog v-model="visible" title="修改上课时间" destroy-on-close>
                <div class="edit-dialog">
                    <el-form>
                        <el-form-item label="日期">
                            <el-date-picker  v-model="classDate"  type="date"  format="YYYY-MM-DD" value-format="YYYY-MM-DD"   placeholder="选择日期" @change="getCheckTimeList"></el-date-picker>
                        </el-form-item>
                        <el-form-item label="上课时间">
                            <el-checkbox
                                v-model="checkAll"
                                :indeterminate="isIndeterminate"
                                @change="handleCheckAllChange"
                            >全选</el-checkbox
                            >
                            <el-checkbox-group
                                v-model="checkTimeList"
                                @change="handleCheckedChange"
                            >
                                <el-checkbox
                                    v-for="item in configLessonTime"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                >{{ item.name }}</el-checkbox
                                >
                            </el-checkbox-group>
                        </el-form-item>
                    </el-form>
                </div>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="visible = false">取消</el-button>
                        <el-button type="primary" @click="saveLessonTime">
                            确定
                        </el-button>
                    </div>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import http from '/admin/support/http'
import { Code } from '/admin/enum/app'
import Message from '/admin/support/message'
import Http from '/admin/support/http'
const statusTagColor = reactive({
    4: { label: '已完成', value: 'success' },
    2: { label: '进行中', value: 'primary' },
    1: { label: '未开始', value: 'info' }
})
const timeArr = ref([])
const query = reactive({
    start_time: '',
    end_time: '',
})

const cancel = (id: any) => {
    Message.confirm('确定取消预约吗？', async () => {
        const { data } = await Http.post('/reservation/cancel', { id: id })
        if (data.code === Code.SUCCESS) {
            search()
            Message.success('取消成功')
        } else {
            Message.error(data.message)
        }
    })
}

// 日历table 的头部配置
const headerConfig = ref<any>([])
const tableData = ref([])
const tranformData = (data: any) => {
    let result = []
    for (let i = 0; i < configLessonTime.value.length; i++) {
        let obj = {
            time: configLessonTime.value[i].name,
            customerList: {},
        }
        for (let j = 0; j < data.length; j++) {
            if (data[j].time) {
                for (let k = 0; k < data[j].time.length; k++) {
                    if (configLessonTime.value[i].id === data[j].time[k].id) {
                        obj.customerList[data[j].date] = data[j].time[k]
                    }
                }
            }
        }
        result.push(obj)
    }
    return result
}

const getHeaderConfig = (data: any) => {
    let result = [{  prop: 'time',  label: '时间', }]
    for (let i = 0; i < data.length; i++) {
        result.push({
            prop: data[i].date,
            label: data[i].week,
        })
    }
    return result
}

const configLessonTime = ref([])
const checkTimeList = ref([])


const visible = ref(false)
const checkAll = ref(false)
const isIndeterminate = ref(false)
const handleCheckAllChange = (val: boolean) => {
    checkTimeList.value = val ? configLessonTime.value.map((item) => {
        return item.id
    }) : []
    isIndeterminate.value = false
}
const handleCheckedChange = (value: string[]) => {
    const checkedCount = value.length
    checkAll.value = checkedCount === configLessonTime.value.length
    isIndeterminate.value = checkedCount > 0 && checkedCount < checkTimeList.value.length
}

const classDate = ref('')

//修改上课时间
const editCourse = () => {
    visible.value = true
}
//获系统上课时间
const getConfigLessonTime = (() => {
    http.get('/configuration/times')
        .then(r => {
            if (r.data.code === Code.SUCCESS) {
                let data = r.data.data
                configLessonTime.value = data.map((item: any) => {
                    return {
                        id: item.id,
                        name: item.time_str,
                    }
                })
            } else {
                Message.error(r.data.message)
            }
        })
        .finally(() => {
        })
})
//获取当前日期的上课信息
const getCheckTimeList = (() => {
    http.post('/teacherLesson/detail', {date: classDate.value})
        .then(r => {
            if (r.data.code === Code.SUCCESS) {
                let data = r.data.data
                checkTimeList.value = data?.time_ids
            } else {
                Message.error(r.data.message)
            }
        })
        .finally(() => {
        })
})
//保存
const saveLessonTime = (() => {
    if (!classDate.value) {
        Message.error('请选择日期')
        return
    }
    http.post('/teacherLesson/update', {date: classDate.value, time_ids: checkTimeList.value.join(',')})
        .then(r => {
            if (r.data.code === Code.SUCCESS) {
                Message.success('修改成功')
                visible.value = false
            } else {
                Message.error(r.data.message)
            }
        })
        .finally(() => {
        })
})

const search = () => {
    query.start_time = timeArr.value[0] || ''
    query.end_time = timeArr.value[1] || ''
    http.get('/teacherLesson/list', query)
        .then(r => {
            if (r.data.code === Code.SUCCESS) {
                let data = r.data.data
                tableData.value = tranformData(data)
                headerConfig.value = getHeaderConfig(data)

                console.log(tableData.value, 'tableData')
            } else {
                Message.error(r.data.message)
            }
        })
        .finally(() => {
        })
}

const reset = () => {
    query.start_time = ''
    query.end_time = ''
    timeArr.value = []
    search()
}
getConfigLessonTime()
search()
</script>

<style scoped lang="scss">
.course-list {
    height: calc(100vh - 120px);
}

.course-table {
    width: 100%;
    background: #fff;
    overflow: scroll;
    .table {
        border: 1px solid #ebeef5;
        border-radius: 8px;
        table-layout: fixed;
        .course-header {
            height: 60px;
            td {
                text-align: center;
                border-right: 1px solid #ebeef5;
                border-bottom: 1px solid #e1e4e8;
            }
        }
        .course-tr {
            border-bottom: 1px solid #e1e4e8;
            .time {
                width: 100px;
                text-align: center;
                border-right: 1px solid #ebeef5;
            }
            .course-item {
                border-right: 1px solid #ebeef5;
                height: 110px;
                padding: 4px;
                .active {
                    width: 192px;
                    height: 100%;
                    color: #7C93C3;
                    background: #DFF5FF;
                    border-radius: 4px;
                    padding: 10px;
                }
            }
        }
    }
}
.edit-dialog {
    padding: 36px;
}
</style>
